package com.gams.springboot.config;


import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author tql
 * @current springboot
 * @create 2021-09-19-16:57
 */
@Configuration
public class ShiroConfig {
    //ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
         ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
         //配置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro的内置过滤器
        /*
        1.anon 无需认证就可以访问
        2.authc 必须认证才能访问
        3.user 必须有记住我功能 才能用
        4.perms 对用于某个资源的权限才能访问
        5.role  拥有某个角色权限才能访问
        * */
        Map<String, String> filterMap = new LinkedHashMap<>();
        // 设置免认证 url
        filterMap.put("/login", "anon");

//        filterMap.put("/css/**", "anon");
//        filterMap.put("/js/**", "anon");
//        filterMap.put("/lib/**", "anon");

        filterMap.put("page/menu.html","perms[menu:view]");
        filterMap.put("page/table.html","perms[user:view]");
        filterMap.put("page/table1.html","perms[role:view]");
        filterMap.put("/roleList","perms[user:add]");
        filterMap.put("/deleteUser","perms[user:delete]");
        filterMap.put("/edit","perms[user:update]");
        filterMap.put("/searchUser","perms[user:select]");
        filterMap.put("page/table/add1.html","perms[role:add]");
        filterMap.put("/edit1","perms[role:update]");
        filterMap.put("/deleteRole","perms[role:delete]");
        filterMap.put("page/addmenu.html","perms[menu:add]");
        filterMap.put("/editMenu","perms[menu:update]");
        filterMap.put("/deleteMenu","perms[menu:delete]");


//         filterMap.put("/*","authc");
        bean.setFilterChainDefinitionMap(filterMap);

        //设置登录的请求
        bean.setLoginUrl("/loginSubmit");
        //设置登陆成功的页面
        bean.setSuccessUrl("/index");
        //设置未授权页面
        bean.setUnauthorizedUrl("/noauth");
        return bean;
    }

    //DefaultWebSecurityManager 2.
    @Bean(name="securityManager")
     public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
          DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
          //关联userRealm
          securityManager.setRealm(userRealm);
          return securityManager;
     }
    // 创建Realm 对象 1.
    @Bean(name="userRealm")
    public UserRealm userRealm(){
        return new UserRealm();
    }
}
